package com.benew.ntt.ydeval.view.wiget

import android.content.Context
import android.graphics.drawable.AnimationDrawable
import android.text.SpannableStringBuilder
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import com.benew.ntt.evaluate.EvalScore
import com.benew.ntt.evaluate.constant.EvalStatus
import com.benew.ntt.ydeval.R
import com.benew.ntt.ydeval.YDResultParse
import com.benew.ntt.ydeval.databinding.EvalLayoutEvaluateBinding
import com.benew.ntt.ydeval.view.EvalEntity
import com.benew.ntt.ydeval.view.EvalManager
import com.benew.ntt.ydeval.view.IEvalViewListener
import com.blankj.utilcode.util.GsonUtils
import com.ntt.core.nlogger.NLogger

class EvalView(context: Context) : RelativeLayout(context), View.OnClickListener {
    private val TAG = javaClass.simpleName

    private var mBinding =
        EvalLayoutEvaluateBinding.inflate(LayoutInflater.from(context), this)

    private val mRecordDrawable = mBinding.ivVoiceInput.drawable as AnimationDrawable
    var mListener: IEvalViewListener? = null
    val mContent = SpannableStringBuilder()
    var mReciteMode = false
    var mEvalEntity: EvalEntity? = null

    init {
        mBinding.ivClose.setOnClickListener(this)
        mBinding.ivVoiceInput.setOnClickListener(this)
        mBinding.ivAgain.setOnClickListener(this)
        mBinding.ivRecord.setOnClickListener(this)
        mBinding.ivOriginal.setOnClickListener(this)
        mBinding.ivArrowLeft.setOnClickListener(this)
        mBinding.ivArrowRight.setOnClickListener(this)
    }

    /**
     * 开始评测
     */
    fun beforeEval(evalEntity: EvalEntity?) {
        mEvalEntity = evalEntity
        NLogger.d(TAG, "view 评测开始:" + GsonUtils.toJson(evalEntity))
        this.mReciteMode = (evalEntity?.reciteMode == true)
        mContent.clear()
        if (!mReciteMode) {
            mContent.append(evalEntity?.content ?: "")
        }
        mBinding.tvContent.text = mContent

        mBinding.tvEval.text = "播放原音中..."

        if (mBinding.tvEval.visibility != View.VISIBLE) {
            mBinding.tvEval.visibility = View.VISIBLE
        }
        if (mBinding.ivVoiceInput.visibility != View.GONE) {
            mBinding.ivVoiceInput.visibility = View.GONE
        }
        if (mBinding.layoutBtn.visibility != View.GONE) {
            mBinding.layoutBtn.visibility = View.GONE
        }
        if (mBinding.ivStar.visibility != View.GONE) {
            mBinding.ivStar.visibility = View.GONE
        }
        if (evalEntity?.switchBtn == true) {
            mBinding.ivArrowLeft.visibility = View.VISIBLE
            mBinding.ivArrowRight.visibility = View.VISIBLE
        } else {
            mBinding.ivArrowLeft.visibility = View.INVISIBLE
            mBinding.ivArrowRight.visibility = View.INVISIBLE
        }

        if (mRecordDrawable.isRunning) {
            mRecordDrawable.stop()
        }
        stopPlayRecord()
        stopPlayOriginal()
    }

    /**
     * 开始评测
     */
    fun startEval(evalEntity: EvalEntity?) {
        mEvalEntity = evalEntity
        NLogger.d(TAG, "view 评测开始:" + GsonUtils.toJson(evalEntity))
        this.mReciteMode = (evalEntity?.reciteMode == true)
        mContent.clear()
        if (!mReciteMode) {
            mContent.append(evalEntity?.content ?: "")
        }
        mBinding.tvContent.text = mContent

        mBinding.tvEval.text = ""

        if (mBinding.tvEval.visibility != View.VISIBLE) {
            mBinding.tvEval.visibility = View.VISIBLE
        }
        if (mBinding.ivVoiceInput.visibility != View.GONE) {
            mBinding.ivVoiceInput.visibility = View.GONE
        }
        if (mBinding.layoutBtn.visibility != View.GONE) {
            mBinding.layoutBtn.visibility = View.GONE
        }
        if (mBinding.ivStar.visibility != View.GONE) {
            mBinding.ivStar.visibility = View.GONE
        }
        if (evalEntity?.switchBtn == true) {
            mBinding.ivArrowLeft.visibility = View.VISIBLE
            mBinding.ivArrowRight.visibility = View.VISIBLE
        } else {
            mBinding.ivArrowLeft.visibility = View.INVISIBLE
            mBinding.ivArrowRight.visibility = View.INVISIBLE
        }


        if (mRecordDrawable.isRunning) {
            mRecordDrawable.stop()
        }
        stopPlayRecord()
        stopPlayOriginal()
        //不要那么快显示评测连接中
        postDelayed({
            if (EvalManager.getEvalStatus() == EvalStatus.CONNECTING) {
                mBinding.tvEval.text = "评测连接中..."
            }
        }, 1000)
    }

    /**
     * 开始录音
     */
    fun startRecord() {
        NLogger.d(TAG, "view 开始录音")
        mBinding.tvEval.text = "评测中"
        if (mBinding.tvEval.visibility != View.VISIBLE) {
            mBinding.tvEval.visibility = View.VISIBLE
        }
        if (mBinding.ivVoiceInput.visibility != View.VISIBLE) {
            mBinding.ivVoiceInput.visibility = View.VISIBLE
        }
        if (mBinding.layoutBtn.visibility != View.GONE) {
            mBinding.layoutBtn.visibility = View.GONE
        }
        if (mBinding.ivStar.visibility != View.GONE) {
            mBinding.ivStar.visibility = View.GONE
        }
        if (!mRecordDrawable.isRunning) {
            mRecordDrawable.start()
        }
        stopPlayRecord()
        stopPlayOriginal()
    }

    /**
     * 评测进度
     */
    fun setProgress(progress: String?) {
        if (mReciteMode) {
            YDResultParse.parseReciteProgress(progress, mContent)
            mBinding.tvContent.text = mContent
        } else {
            if (mContent.isNotEmpty()) {
                YDResultParse.parseProgress(progress, mContent)
                mBinding.tvContent.text = mContent
            }
        }

    }

    /**
     * 录音结束
     */
    fun recordEnd() {
        NLogger.d(TAG, "view 录音结束:$mContent")
        if(mBinding.ivStar.visibility == View.VISIBLE){
            return
        }
        mBinding.ivStar.visibility = View.GONE

        mBinding.tvEval.text = "正在评分..."
        if (mBinding.tvEval.visibility != View.VISIBLE) {
            mBinding.tvEval.visibility = View.VISIBLE
        }
        if (mBinding.ivVoiceInput.visibility != View.GONE) {
            mBinding.ivVoiceInput.visibility = View.GONE
        }
        if (mBinding.layoutBtn.visibility != View.GONE) {
            mBinding.layoutBtn.visibility = View.GONE
        }
        if (mRecordDrawable.isRunning) {
            mRecordDrawable.stop()
        }
        stopPlayRecord()
        stopPlayOriginal()
    }

    /**
     * 显示异常
     */
    fun showError(errorMsg: String?) {
        NLogger.d(TAG, "view 显示异常:$mContent")
        mBinding.tvAgain.text = if (errorMsg.isNullOrBlank()) {
            "评测失败，请重新评测"
        } else {
            errorMsg
        }
        if (mBinding.tvEval.visibility != View.GONE) {
            mBinding.tvEval.visibility = View.GONE
        }
        if (mBinding.ivVoiceInput.visibility != View.GONE) {
            mBinding.ivVoiceInput.visibility = View.GONE
        }
        if (mBinding.layoutBtn.visibility != View.VISIBLE) {
            mBinding.layoutBtn.visibility = View.VISIBLE
        }
        if (mBinding.groupOriginal.visibility != View.GONE) {
            mBinding.groupOriginal.visibility = View.GONE
        }
        if (mBinding.groupRecord.visibility != View.GONE) {
            mBinding.groupRecord.visibility = View.GONE
        }
        if (mBinding.groupAgain.visibility != View.VISIBLE) {
            mBinding.groupAgain.visibility = View.VISIBLE
        }
        if (mBinding.ivStar.visibility != View.GONE) {
            mBinding.ivStar.visibility = View.GONE
        }
        if (mRecordDrawable.isRunning) {
            mRecordDrawable.stop()
        }
        stopPlayRecord()
        stopPlayOriginal()
    }


    /**
     * 显示分数
     */
    fun showResult(text: SpannableStringBuilder, score: Double) {
        NLogger.d(TAG, "view 显示分数", "text=$text", "score=$score")
        setScore(score)

        //显示结果
        if (text.toString().isNotEmpty() && text != mContent) {
            mContent.clear()
            mContent.append(text)
            mBinding.tvContent.text = mContent
        }

        stopPlayRecord()
        stopPlayOriginal()

        mBinding.tvAgain.text = "重新评测"
        if (mBinding.tvEval.visibility != View.GONE) {
            mBinding.tvEval.visibility = View.GONE
        }
        if (mBinding.ivVoiceInput.visibility != View.GONE) {
            mBinding.ivVoiceInput.visibility = View.GONE
        }
        if (mBinding.layoutBtn.visibility != View.VISIBLE) {
            mBinding.layoutBtn.visibility = View.VISIBLE
        }

        if (!mEvalEntity?.audioUrl.isNullOrBlank()) {
            if (mBinding.groupOriginal.visibility != View.VISIBLE) {
                mBinding.groupOriginal.visibility = View.VISIBLE
            }
        } else {
            if (mBinding.groupOriginal.visibility != View.GONE) {
                mBinding.groupOriginal.visibility = View.GONE
            }
        }
        if (mBinding.groupRecord.visibility != View.VISIBLE) {
            mBinding.groupRecord.visibility = View.VISIBLE
        }
        if (mBinding.groupAgain.visibility != View.VISIBLE) {
            mBinding.groupAgain.visibility = View.VISIBLE
        }
        if (mBinding.ivStar.visibility != View.VISIBLE) {
            mBinding.ivStar.visibility = View.VISIBLE
        }
        if (mRecordDrawable.isRunning) {
            mRecordDrawable.stop()
        }
    }

    /**
     * 播放结果音效
     */
    private fun setScore(score: Double) {
        when {
            score >= EvalScore.STAR_FIVE -> {
                mBinding.ivStar.setImageResource(R.drawable.eval_score_star5)
            }
            score >= EvalScore.STAR_FOUR -> {
                mBinding.ivStar.setImageResource(R.drawable.eval_score_star4)
            }
            score >= EvalScore.STAR_THREE -> {
                mBinding.ivStar.setImageResource(R.drawable.eval_score_star3)
            }
            score >= EvalScore.STAR_TWO -> {
                mBinding.ivStar.setImageResource(R.drawable.eval_score_star2)
            }
            score >= EvalScore.STAR_ONE -> {
                mBinding.ivStar.setImageResource(R.drawable.eval_score_star1)
            }
            else -> {
                mBinding.ivStar.setImageResource(R.drawable.eval_score_star0)
            }
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            //点击关闭
            mBinding.ivClose -> {
                mListener?.clickClose()
            }
            //点击停止
            mBinding.ivVoiceInput -> {
                mListener?.clickStopEval()
            }
            //点击上一个
            mBinding.ivArrowLeft -> {
                mListener?.clickPre()
            }
            //点击下一个
            mBinding.ivArrowRight -> {
                mListener?.clickNext()
            }
            //重新评测
            mBinding.ivAgain -> {
                mListener?.clickAgain()
            }
            //点击播放录音
            mBinding.ivRecord -> {
                mListener?.clickRecord()
            }
            //点击播放原音频
            mBinding.ivOriginal -> {
                mListener?.clickOriginal()
            }
        }
    }

    /**
     * 播放录音
     */
    fun playRecord() {
        mBinding.ivRecord.setImageResource(R.drawable.eval_anim_playing)
        val drawable = mBinding.ivRecord.drawable
        if (drawable is AnimationDrawable) {
            if (!drawable.isRunning) {
                drawable.start()
            }
        }
        stopPlayOriginal()
    }

    /**
     * 停止播放录音
     */
    fun stopPlayRecord() {
        val drawable = mBinding.ivRecord.drawable
        if (drawable is AnimationDrawable) {
            if (drawable.isRunning) {
                drawable.stop()
            }
        }
        mBinding.ivRecord.setImageResource(R.drawable.eval_icon_record)
    }

    /**
     * 播放原音
     */
    fun playOriginal() {
        mBinding.ivOriginal.setImageResource(R.drawable.eval_anim_playing)
        val drawable = mBinding.ivOriginal.drawable
        if (drawable is AnimationDrawable) {
            if (!drawable.isRunning) {
                drawable.start()
            }
        }
        stopPlayRecord()
    }

    /**
     * 停止播放原音
     */
    fun stopPlayOriginal() {
        val drawable = mBinding.ivOriginal.drawable
        if (drawable is AnimationDrawable) {
            if (drawable.isRunning) {
                drawable.stop()
            }
        }
        mBinding.ivOriginal.setImageResource(R.drawable.eval_icon_original)
    }

}